﻿using System.Linq.Expressions;
using Basic.FormDAL;
using Basic.FormModel.DB;
using Basic.FormModel.QueryTable;
using Basic.FormRemoteModel.QueryTable.Model;
using WeDonekRpc.Helper;

namespace Basic.FormCollect.lmpl
{
    internal class QueryTableCollect : IQueryTableCollect
    {
        private readonly IPhysicalQueryTableDAL _Service;

        public QueryTableCollect ( IPhysicalQueryTableDAL service )
        {
            this._Service = service;
        }
        public DBPhysicalQueryTable Get ( long id )
        {
            return this._Service.Get(id);
        }
        public Result Get<Result> ( long id ) where Result : class, new()
        {
            return this._Service.Get<Result>(id);
        }
        public void Delete ( DBPhysicalQueryTable table )
        {
            this._Service.Delete(table.Id);
        }
        public long Add ( PhyQueryTableAdd data, bool isMainTable )
        {
            if ( this._Service.IsExists(a => a.TableName == data.TableName) )
            {
                throw new ErrorException("form.query.table.name.repeat");
            }
            return this._Service.Add(data, isMainTable);
        }
        public bool Set ( DBPhysicalQueryTable table, PhyQueryTableSet set )
        {
            if ( table.TableName != set.TableName && this._Service.IsExists(a => a.TableName == set.TableName) )
            {
                throw new ErrorException("form.query.table.name.repeat");
            }
            return this._Service.Update(table, set);
        }
        public PhyQueryTable[] Gets ( long formId )
        {
            return this._Service.Gets<PhyQueryTable>(a => a.FormId == formId);
        }
        public Result[] GetsByFormId<Result> ( long formId, Expression<Func<DBPhysicalQueryTable, Result>> selector ) where Result : class, new()
        {
            return this._Service.Gets<Result>(a => a.FormId == formId, selector);
        }
        public Dictionary<long, string> GetTableName ( long[] ids )
        {
            return this._Service.Gets(a => ids.Contains(a.Id), a => new { a.Id, a.TableName }).ToDictionary(a => a.Id, a => a.TableName);
        }
        public PhyQueryTable[] Gets ( long[] ids )
        {
            return this._Service.Gets<PhyQueryTable>(ids);
        }
        public void Clear ( long formId )
        {
            long[] ids = this._Service.Gets(a => a.FormId == formId, a => a.Id);
            if ( !ids.IsNull() )
            {
                this._Service.Delete(ids);
            }
        }

        public long GetMainTableId ( long formId )
        {
            return this._Service.Find<long>(a => a.FormId == formId && a.IsMainTable, a => a.Id);
        }
    }
}
